//
//  WalletViewController.m
//  AppleMarket
//
//  Created by yangy on 02/11/2018.
//  Copyright © 2018 szgsy. All rights reserved.
//

#import "WalletViewController.h"
// model
#import "CoinAssetModel.h"
#import "AddressModel.h"
// view
#import "WalletAddressCell.h"
// controller
#import "NewAddressViewController.h"

@interface WalletViewController () <UITableViewDelegate,UITableViewDataSource,SWTableViewCellDelegate>
@property (nonatomic, strong) UIButton *addButton;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray<AddressModel*> *dataList;
@end

@implementation WalletViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"钱包地址管理";
    [self initViews];
}

- (void) initViews
{
    [self.view addSubview:self.addButton];
    [self.view addSubview:self.tableView];
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.view);
        make.left.right.mas_equalTo(self.view);
        make.bottom.mas_equalTo(self.addButton.mas_top);
    }];
    [_addButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(self.view);
        make.bottom.mas_equalTo(self.view);
        make.height.mas_equalTo(50);
    }];
}


- (void) fetchAddreessList
{
    [NetRequest request_GetUserWithdrawAccountListWithCeId:self.coinModel.CurrencyID completeHandler:^(id  _Nonnull responseObj) {
        [self.tableView.mj_header endRefreshing];
        if([[responseObj objectForKey:@"Status"] boolValue]){
            NSArray *data = [responseObj objectForKey:@"Data"];
            self.dataList = [[[data.rac_sequence map:^id _Nullable(id  _Nullable value) {
                return [AddressModel yy_modelWithDictionary:value];
            }] array] mutableCopy];
            [self.tableView reloadData];
        }
    } fail:^(NSError * _Nonnull error) {
        [self.tableView.mj_header endRefreshing];
    }];
}

#pragma mark - 删除地址
- (void) request_DeleteAddress:(AddressModel*) model
{
    [SVProgressHUD show];
    [NetRequest request_DoDeleteUserWithdrawAccountWithId:model.ID completeHandler:^(id  _Nonnull responseObj) {
        if([[responseObj objectForKey:@"Status"] boolValue]){
            [SVProgressHUD showInfoWithStatus:@"钱包地址删除成功"];
            NSInteger index = [self.dataList indexOfObject:model];
            [self.dataList removeObject:model];
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:index inSection:0];
            [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
        }else{
            [SVProgressHUD showInfoWithStatus:[responseObj objectForKey:@"Msg"]];
        }
    } fail:^(NSError * _Nonnull error) {
        [SVProgressHUD showInfoWithStatus:@"网络异常"];
    }];
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    WalletAddressCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([WalletAddressCell class])];
    if(cell == nil){
        cell = [[WalletAddressCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:NSStringFromClass([WalletAddressCell class])];
        UIButton *rightButton = [UIButton cm_ButtonWithTitle:@"删除" font:kFont(17) titleColor:[UIColor whiteColor] bgColor:kColorWithHex(0xF5174D)];
        NSArray *buttons = [NSArray arrayWithObject:rightButton];
        [cell setRightUtilityButtons:buttons WithButtonWidth:100];
        cell.delegate = self;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    [cell updateWithModel:self.dataList[indexPath.row]];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 115;
}

- (void)swipeableTableViewCell:(SWTableViewCell *)cell didTriggerRightUtilityButtonWithIndex:(NSInteger)index
{
    // 删除
    UIAlertController *alaterVC = [UIAlertController alertControllerWithTitle:@"提示" message:@"确认删除该钱包地址吗?" preferredStyle:UIAlertControllerStyleAlert];
    [alaterVC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [alaterVC addAction:[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
        [self request_DeleteAddress:self.dataList[indexPath.row]];
    }]];
    [self presentViewController:alaterVC animated:YES completion:nil];
}

#pragma mark - lazy load
- (UITableView *)tableView
{
    if(!_tableView){
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        [_tableView setDelegate:self];
        [_tableView setDataSource:self];
        [_tableView setTableFooterView:[UIView new]];
        [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
        [_tableView setMj_header:[MJRefreshNormalHeader headerWithRefreshingBlock:^{
            [self fetchAddreessList];
        }]];
        [_tableView.mj_header beginRefreshing];
    }
    return _tableView;
}

- (UIButton *)addButton
{
    if(!_addButton){
        NSString *text = [NSString stringWithFormat:@"添加%@钱包地址",self.coinModel.Unit];
        _addButton = [UIButton cm_ButtonWithTitle:text font:kFont(15) titleColor:[UIColor whiteColor] bgColor:kColorWithHex(0x3291EB)];
        @weakify(self);
        [[_addButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            @strongify(self);
            NewAddressViewController *newAddressVC = [[NewAddressViewController alloc] init];
            newAddressVC.assetModel = self.coinModel;
            newAddressVC.newCompleteHandler = ^{
                [self fetchAddreessList];
            };
            [self bh_PushViewController:newAddressVC hiddenTabbar:YES];
        }];
    }
    return _addButton;
}

@end
